﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web.Security;
using System.Windows.Forms;
using SBACN.WebSite.Cache;
using SBACN.WebSite.Code;
using SBACN.WebSite.Common;
using SBACN.WebSite.Models;

namespace SBACN.SBACNTools
{
	public partial class Tools : Form
	{
		public Tools()
		{
			InitializeComponent();
		}

		private void btn_OpenExcel_Click(object sender, EventArgs e)
		{
			this.openExcelDialog.ShowDialog();
		}

		private void btn_CreateAccount_Click(object sender, EventArgs e)
		{
			if(string.IsNullOrWhiteSpace(this.txt_FilePath.Text))
			{
				MessageBox.Show("请选择Excel文件");
				return;
			}

			try
			{
				DataTable dt = ExcelAccess.GetExcelRows(this.txt_FilePath.Text, "人力资源").Tables[0];
				CreateUserBySheet(dt);
				dt = ExcelAccess.GetExcelRows(this.txt_FilePath.Text, "一般联络人").Tables[0];
				CreateUserBySheet(dt);
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}

		private void CreateUserBySheet(DataTable dt)
		{
			try
			{
				IDictionary<string, KeyValuePair<User, TB_Role>> userList = new Dictionary<string, KeyValuePair<User, TB_Role>>();
				string errormsg = string.Empty;
				//foreach(DataRow dr in dt.Rows)
				for (int i = 0; i < dt.Rows.Count; i++)
				{
					var dr = dt.Rows[i];
					/*会员单位	使用人	Email	用户类型*/
					string username = dr["Email"].ToString();
					string nickname = dr["使用人"].ToString();
					string email = dr["EMail"].ToString();
					string roleName = dr["用户类型"].ToString();
					string memberName = dr["会员单位"].ToString();
					var member = SBACN.WebSite.DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_Member>(p => p.Name == memberName);
					var role = RoleCache.Instance.CacheList.Where(p => p.Name == roleName).FirstOrDefault();
					if (string.IsNullOrWhiteSpace(username))
					{
						errormsg += "第" + i + "行数据存在错误:用户名不能为空!\r\n";
						continue;
					}
					else if (string.IsNullOrWhiteSpace(email) || !(email.LastIndexOf(".") > (email.IndexOf("@") + 1) && email.IndexOf("@") > 1 && email.LastIndexOf(".") < email.Length - 2))
					{
						errormsg += "第" + i + "行数据存在错误:邮件地址不能为空或邮件地址不正确!\r\n";
						continue;
					}
					else if (string.IsNullOrWhiteSpace(roleName) || role == null)
					{
						errormsg += "第" + i + "行数据存在错误:用户类型设置不正确!\r\n";
						continue;
					}
					else if (member == null)
					{
						errormsg += "第" + i + "行数据存在错误:会员单位设置不正确!\r\n";
						continue;
					}
					else
					{
						string password = BasePage.GeneratePassword(8);
						TB_User user = SBACN.WebSite.DAL.DALHelper.Instance.GetObject<TB_User>("UserName", username);
						if (user != null)
						{
							errormsg += "第" + i + "行数据存在错误:该用户名已存在!\r\n";
							continue;
						}
						else
						{
							user = SBACN.WebSite.DAL.DALHelper.Instance.Create<TB_User>();
							user.UserName = username;
							string passwordmd5 = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5").ToLower();
							user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(passwordmd5, "MD5").ToLower();
							user.NickName = nickname;
							user.EMail = email;
							user.Status = true;
							user.MemberID = member.ID;
							user.CreateBy = "system";
							user.CreateDate = DateTime.Now;
							User u = new User();
							u.RawPassword = password;
							u.InnerUser = user;
							userList.Add(user.UserName, new KeyValuePair<User, TB_Role>(u, role));
						}
					}
				}

				if(!string.IsNullOrWhiteSpace(errormsg))
				{
					MessageBox.Show(errormsg);
					return;
				}

				#region 验证通过，更改数据库数据,创建新用户
				foreach (var userKVP in userList.Values)
				{
					var user = userKVP.Key.InnerUser;
					var role = userKVP.Value;
					SBACN.WebSite.DAL.DALHelper.Instance.Add(user);
					SBACN.WebSite.DAL.DALHelper.Instance.SaveChanges();

					TB_UserInRoles roleRelate = SBACN.WebSite.DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_UserInRoles>(p => p.UserName == user.UserName);
					if (roleRelate == null)
					{
						roleRelate = SBACN.WebSite.DAL.DALHelper.Instance.Create<TB_UserInRoles>();
						roleRelate.RoleID = role.ID;
						roleRelate.UserName = user.UserName;
						SBACN.WebSite.DAL.DALHelper.Instance.Add(roleRelate);
					}
					SBACN.WebSite.DAL.DALHelper.Instance.SaveChanges();

					TB_SystemConfig config = SystemConfigCache.Instance["00090007"].Where(p => p.Code == "5").FirstOrDefault();
					if (config != null && config.Status)
					{
						Mail.Instance.SendEMail(config.Name.Replace("$Name", user.UserName), config.Value.Replace("$Name", user.UserName).Replace("$Password", userKVP.Key.RawPassword), user.EMail);
					}
				}
				#endregion
			}
			catch (Exception ex)
			{
				MessageBox.Show(ex.Message);
			}
		}
		private void openExcelDialog_FileOk(object sender, CancelEventArgs e)
		{
			this.txt_FilePath.Text = openExcelDialog.FileName;
		}

		class User
		{
			public string RawPassword;
			public TB_User InnerUser;
		}
	}
}
